<?php
namespace app\api\command;

use app\api\library\curd\BuildCurd;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

class Crud extends Command
{
    protected function configure()
    {
        $this->setName('crud')
            ->addOption('table', 't', Option::VALUE_REQUIRED, '主表名', null)
            ->addOption('controllerFilename', 'c', Option::VALUE_REQUIRED, '控制器名', null)
            ->addOption('modelFilename', 'm', Option::VALUE_REQUIRED, '主表模型文件名', null)
            ->addOption('validateFilename', null, Option::VALUE_REQUIRED, '验证器名', null)
            ->addOption('validateFields', null, Option::VALUE_REQUIRED | Option::VALUE_IS_ARRAY, '验证器校验的字段', null)
            ->setDescription('一键curd命令服务');
    }

    protected function execute(Input $input, Output $output)
    {
        $table              = $input->getOption('table');
        $controllerFilename = $input->getOption('controllerFilename');
        $modelFilename      = $input->getOption('modelFilename');
        $validateFilename   = $input->getOption('validateFilename');
        $output->writeln("crud:");

        try {
            $build = (new BuildCurd())->setTable($table);

            !empty($controllerFilename) && $build = $build->setControllerFilename($controllerFilename);
            !empty($modelFilename) && $build      = $build->setModelFilename($modelFilename);
            !empty($validateFilename) && $build   = $build->setValidateFilename($validateFilename);

            $build = $build->render();

            $result = $build->create();
            $output->writeln("自动生成CURD成功");
            $output->writeln(">>>>>>>>>>>>>>>");
            foreach ($result as $vo) {
                $output->writeln($vo);
            }
            $output->writeln(">>>>>>>>>>>>>>>");
        } catch (\Exception $e) {
            $output->writeln($e->getMessage());
            return false;
        }
    }
}
